// @ts-ignore
import md5 from "md5"
import {util} from "@/common/util";
import { UserInfo,MenuElement,EnptElement,SelectElement } from "@/common/zct-types"
import { AnyParams } from "@/common/httptypes";

const loginUserCacheKey = "zct"
const loginUserSecretKey = "zct_token"
const loginUserTokenSecret = "asdfasdfqaewrf34trqrgjk$%@$^$%&^#%^!31gfdgasdada"



// export const ROUTER_DATA =JSON.parse(JSON.stringify(require('./router-cofig.json'))) ;


export class User {
    token: string | undefined;
    userInfo: UserInfo | undefined;
    menu: MenuElement[] = [];
    menuMapping: MenuElement[] = [];
    btnMapping:string[] = []
    enptTypeToiD:AnyParams<string>  | undefined;
    enptTypeToSelect:SelectElement[] | undefined;
    exists: boolean | undefined;

    constructor() {
        this.exists = false;

    }

    /**
     * 清除缓存
     */
    clear() {
        this.exists = false;
        localStorage.removeItem(loginUserCacheKey);
        localStorage.removeItem(loginUserSecretKey);
        this.token = undefined;
        this.userInfo = undefined;
        this.menu = [];
        this.menuMapping = []
        this.btnMapping = []
        this.enptTypeToiD = undefined
        this.enptTypeToSelect = undefined
    }

    /**
     * 同步缓存
     */
    storage() {
        const str = JSON.stringify(this)
        const sign = md5(str + "&" + loginUserTokenSecret)
        localStorage.setItem(loginUserCacheKey, str);
        localStorage.setItem(loginUserSecretKey, sign);

    }

    /**
     * 修改登录信息
     * @param data
     */
    save(data: User | {}) {
        // @ts-ignore
        Object.keys(data).forEach(p => this[p] = data[p])
    }

    /**
     * 修改登录信息并且保存
     * @param data
     */

    saveAndFlush(data: User | {}) {
        // @ts-ignore
        Object.keys(data).forEach(p => this[p] = data[p])
        this.storage()
    }

    /**
     * 懒加载获取User
     */
    sync(): User {
        if (this.exists) {
            return this;
        } else {
            this.reload()
            return this;
        }
    }

    /**
     * 重载User
     */
    reload() {
        const str = localStorage.getItem(loginUserCacheKey);
        if (str && str !== "") {
            const {
                token = undefined,
                userInfo = undefined,
                menu = [],
                menuMapping = [],
                btnMapping = [],
                enptTypeToiD = undefined,
                enptTypeToSelect = undefined
            } = JSON.parse(str)
            const sign = md5(str + "&" + loginUserTokenSecret)
            if (sign === localStorage.getItem(loginUserSecretKey)) {
                this.token = token;
                this.userInfo = userInfo;
                this.menu = menu;
                this.menuMapping = menuMapping
                this.btnMapping = btnMapping
                this.enptTypeToiD = enptTypeToiD
                this.enptTypeToSelect = undefined
                this.exists = true;
            } else {
                this.clear()
            }

        }
    }


    logout() {
        this.clear()
        util.toLogin()
    }

    getMenuList(): MenuElement[] {
        return routerData(this.menuMapping,this.menu);
    };

    getBtnList(){
        return btnData(this.btnMapping,this.menu);
    };
}



function routerData(menuMapping:any,data:any,) {
    for (let i in data) {
        let item = data[i];
        if (item.type === 'menu') {
          // eslint-disable-next-line @typescript-eslint/no-array-constructor
          let children = new Array();
          if (item.children && item.children.length > 0) {
            routerData(children,item.children);
          }
          menuMapping.push({ ...item, children });
        }
      }
      return menuMapping;
}

function btnData(btnMapping:any,data:any,) {
    data.forEach((item:MenuElement) => {
        if (item.code && item.type === "button") {
          btnMapping.push(item.code);
        }
        if (item.children && item.children.length > 0) {
          item.children.forEach((val) => {
            if (val.type === "button") {
                btnMapping.push(val.code);
            }
            if (val.children && val.children.length > 0) {
              btnData(btnMapping,val.children);
            }
          });
        }
      });

      return btnMapping;
}


const LoginUser: User = new User().sync();


export default LoginUser;
